<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <!-- 基础信息 -->
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>基础信息</span>
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产订单号" prop="orderNo">
              <div class="input-with-switch">
                <el-input 
                  v-model="form.orderNo" 
                  placeholder="格式：SCDT+年月日+5位序号，如SCDT2025072500011" 
                  style="width: 70%" 
                  :disabled="systemOrderNo"
                  @input="validateOrderNo" 
                  @blur="validateForm('orderNo')"
                />
                <el-switch
                  v-model="systemOrderNo"
                  class="switch-right"
                  active-text="系统编号"
                  @change="validateForm('orderNo')"
                />
              </div>
              <!-- 移除自定义错误提示，只使用表单验证的错误提示 -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="customerName">
              <el-input 
                v-model="form.customerName" 
                placeholder="请选择客户" 
                readonly
                @blur="validateForm('customerName')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单来源" prop="orderSource">
              <el-input v-model="orderSourceLabel" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
             <el-form-item label="销售订单号">
                <el-input v-model="form.salesOrderNo" placeholder="请选择销售订单号" readonly>
                  <el-button slot="append" icon="el-icon-search" @click="openSalesOrderDialog"></el-button>
                </el-input>
              </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="dict in priorityOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
           <el-col :span="16">
             <el-form-item label="备注" prop="remarks">
                <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入内容" />
              </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="自动生成计划" prop="autoGeneratePlan">
                <el-switch
                  v-model="form.autoGeneratePlan"
                  active-text="是"
                  inactive-text="否"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
                </el-switch>
                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                  开启后将根据产品明细自动生成生产计划
                </div>
              </el-form-item>
           </el-col>
        </el-row>
      </el-card>

      <!-- 产品信息 -->
      <el-card shadow="never" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>产品信息</span>
        </div>
        <el-row>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddProduct">添加产品</el-button>
            </el-col>
        </el-row>
        <el-table :data="productList" style="width: 100%; margin-top: 10px;" border>
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="产品编码" align="center" width="155">
                <template slot-scope="scope">
                    {{ scope.row.productCode }}
                </template>
            </el-table-column>
            <el-table-column label="产品名称" align="center" min-width="200">
                <template slot-scope="scope">
                    {{ scope.row.productName }}
                </template>
            </el-table-column>
            <el-table-column label="规格" align="center" width="150">
                <template slot-scope="scope">
                    {{ scope.row.specification || '—' }}
                </template>
            </el-table-column>
            <el-table-column label="计量单位" prop="unit" align="center" width="100" />
            <el-table-column label="库存状态" align="center" width="150">
                <template slot-scope="scope">
                    <div>
                      <el-tag v-if="scope.row.stockStatus === 'sufficient'" type="success" size="mini">
                        <i class="el-icon-success"></i> 库存充足
                      </el-tag>
                      <el-tag v-else-if="scope.row.stockStatus === 'insufficient'" type="warning" size="mini">
                        <i class="el-icon-warning"></i> 需生产
                      </el-tag>
                      <el-tag v-else type="danger" size="mini">
                        <i class="el-icon-error"></i> 无法生产
                      </el-tag>
                      <div style="margin-top: 5px;">库存: {{ scope.row.quantity_num || 0 }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="需求数量" align="center" width="120">
                <template slot-scope="scope">
                    <el-input-number v-model="scope.row.plannedQty" :min="1" size="small" :precision="0" @change="updateActualProduction(scope.row)"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="实际生产" align="center" width="100">
                <template slot-scope="scope">
                    <span :style="{ color: getActualProductionQty(scope.row) > 0 ? '#E6A23C' : '#67C23A', fontWeight: 'bold' }">
                        {{ getActualProductionQty(scope.row) }}
                    </span>
                    <div style="font-size: 10px; color: #999; margin-top: 2px;">
                        {{ getActualProductionQty(scope.row) > 0 ? '需生产' : '库存足够' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="交付日期" align="center" width="140">
                 <template slot-scope="scope">
                    <el-date-picker v-model="scope.row.deliveryDate" type="date" placeholder="选择日期" size="small" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="80">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
      </el-card>
      
      <div style="text-align: center; margin-top: 30px;">
        <el-button @click="onCancel" :disabled="submitting">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitting" :disabled="submitting">保 存</el-button>
      </div>

    </el-form>

    <!-- 选择销售订单弹窗 -->
    <el-dialog title="选择销售订单" :visible.sync="salesOrderDialogVisible" width="800px" append-to-body>
      <div class="sales-order-dialog">
        <!-- 搜索表单 -->
        <el-form :model="salesOrderQueryParams" ref="salesOrderQueryForm" size="small" :inline="true">
          <el-form-item label="销售订单号" prop="orderCode">
            <el-input
              v-model="salesOrderQueryParams.orderCode"
              placeholder="请输入销售订单号"
              clearable
              @keyup.enter.native="handleSalesOrderQuery"
            />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input
              v-model="salesOrderQueryParams.customerName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter.native="handleSalesOrderQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSalesOrderQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetSalesOrderQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddSalesOrder">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="!selectedSalesOrder" @click="handleUpdateSalesOrder">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!selectedSalesOrder" @click="handleDeleteSalesOrder">删除</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table
          ref="salesOrderTable"
          v-loading="salesOrderLoading"
          :data="salesOrderList"
          @row-click="handleSalesOrderRowSelect"
          highlight-current-row
          row-key="salesOrderId"
          style="width: 100%"
        >
          <el-table-column width="55" align="center">
            <template slot-scope="scope">
              <el-radio :label="scope.row.salesOrderId" v-model="selectedSalesOrderRadio" @change="() => handleSalesOrderRowSelect(scope.row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="销售订单号" align="center" prop="orderCode" min-width="120" />
          <el-table-column label="客户名称" align="center" prop="customerName" min-width="120" show-overflow-tooltip />
          <el-table-column label="订单日期" align="center" width="100">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="交付日期" align="center" width="100">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="80">
            <template slot-scope="scope">
              <span>{{ salesOrderStatusFormat(scope.row) }}</span>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <pagination
          v-show="salesOrderTotal>0"
          :total="salesOrderTotal"
          :page.sync="salesOrderQueryParams.pageNum"
          :limit.sync="salesOrderQueryParams.pageSize"
          @pagination="getSalesOrderList"
        />
      </div>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!selectedSalesOrder" @click="confirmSelectSalesOrder">确 定</el-button>
        <el-button @click="salesOrderDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增销售订单弹窗 -->
    <el-dialog title="新增销售订单" :visible.sync="addSalesOrderDialogVisible" width="800px" append-to-body @closed="resetSalesOrderForm">
      <el-form ref="addSalesOrderForm" :model="salesOrderForm" :rules="salesOrderRules" label-width="100px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="销售订单号" prop="orderCode">
              <div class="input-with-switch">
                <el-input v-model="salesOrderForm.orderCode" placeholder="请输入销售订单号" style="width: 70%" />
                <el-switch
                  v-model="systemSalesOrderNo"
                  class="switch-right"
                  active-text="系统编号"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="salesOrderForm.customerName" placeholder="请输入客户名称" readonly>
                <el-button slot="append" icon="el-icon-search" @click="openSelectCustomerDialog"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker v-model="salesOrderForm.orderDate" type="date" placeholder="选择订单日期" style="width: 100%;" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付日期" prop="deliveryDate">
              <el-date-picker v-model="salesOrderForm.deliveryDate" type="date" placeholder="选择交付日期" style="width: 100%;" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="salesOrderForm.status" placeholder="请选择订单状态" style="width: 100%;">
                <el-option
                  v-for="dict in salesOrderStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="salesOrderForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品信息 -->
        <el-divider content-position="left">产品信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="openSelectProductDialog">添加产品</el-button>
          </el-col>
        </el-row>
        <el-table :data="salesOrderProducts" style="width: 100%; margin-top: 10px;" border>
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="产品编码" prop="productCode" align="center" width="150" />
          <el-table-column label="产品名称" prop="productName" align="center" min-width="200" />
          <el-table-column label="规格" prop="specification" align="center" width="150" />
          <el-table-column label="单位" prop="unit" align="center" width="100" />
          <el-table-column label="单价" prop="price" align="center" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" :precision="2" :min="0" size="mini" controls-position="right" style="width: 100px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="qty" align="center" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.qty" :min="1" :max="scope.row.maxQty" size="mini" controls-position="right" style="width: 100px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="库存状态" align="center" width="150">
            <template slot-scope="scope">
              <div>
                <el-tag v-if="scope.row.stockStatus === 'sufficient'" type="success" size="mini">
                  <i class="el-icon-success"></i> 库存充足
                </el-tag>
                <el-tag v-else-if="scope.row.stockStatus === 'insufficient'" type="warning" size="mini">
                  <i class="el-icon-warning"></i> 需生产
                </el-tag>
                <el-tag v-else type="danger" size="mini">
                  <i class="el-icon-error"></i> 无法生产
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteOrderProduct(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSalesOrderForm" :loading="submitting" :disabled="submitting">确 定</el-button>
        <el-button @click="cancelSalesOrder" :disabled="submitting">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 修改销售订单弹窗 -->
    <el-dialog title="修改销售订单" :visible.sync="updateSalesOrderDialogVisible" width="800px" append-to-body>
      <el-form ref="updateSalesOrderForm" :model="salesOrderForm" :rules="salesOrderRules" label-width="100px">
        <el-row>
          <el-col :span="14">
            <el-form-item label="销售订单号" prop="orderCode">
              <div class="input-with-switch">
                <el-input v-model="salesOrderForm.orderCode" placeholder="请输入销售订单号" :disabled="updateSalesOrderDialogVisible" style="width: 70%" />
                <el-switch
                  v-model="systemSalesOrderNo"
                  class="switch-right"
                  active-text="系统编号"
                  :disabled="updateSalesOrderDialogVisible"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="salesOrderForm.customerName" placeholder="请输入客户名称" readonly>
                <el-button slot="append" icon="el-icon-search" @click="openSelectCustomerDialog"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单日期" prop="orderDate">
              <el-date-picker v-model="salesOrderForm.orderDate" type="date" placeholder="选择订单日期" style="width: 100%;" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付日期" prop="deliveryDate">
              <el-date-picker v-model="salesOrderForm.deliveryDate" type="date" placeholder="选择交付日期" style="width: 100%;" value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="status">
              <el-select v-model="salesOrderForm.status" placeholder="请选择订单状态" style="width: 100%;">
                <el-option
                  v-for="dict in salesOrderStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="salesOrderForm.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 产品信息 -->
        <el-divider content-position="left">产品信息</el-divider>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="openSelectProductDialog">添加产品</el-button>
          </el-col>
        </el-row>
        <el-table :data="salesOrderProducts" style="width: 100%; margin-top: 10px;" border>
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="产品编码" prop="productCode" align="center" width="150" />
          <el-table-column label="产品名称" prop="productName" align="center" min-width="200" />
          <el-table-column label="规格" prop="specification" align="center" width="150" />
          <el-table-column label="单位" prop="unit" align="center" width="100" />
          <el-table-column label="单价" prop="price" align="center" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.price" :precision="2" :min="0" size="mini" controls-position="right" style="width: 100px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="qty" align="center" width="100">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.qty" :min="1" :max="scope.row.maxQty" size="mini" controls-position="right" style="width: 100px"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="库存状态" align="center" width="150">
            <template slot-scope="scope">
              <div>
                <el-tag v-if="scope.row.stockStatus === 'sufficient'" type="success" size="mini">
                  <i class="el-icon-success"></i> 库存充足
                </el-tag>
                <el-tag v-else-if="scope.row.stockStatus === 'insufficient'" type="warning" size="mini">
                  <i class="el-icon-warning"></i> 需生产
                </el-tag>
                <el-tag v-else type="danger" size="mini">
                  <i class="el-icon-error"></i> 无法生产
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteOrderProduct(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateSalesOrderForm">确 定</el-button>
        <el-button @click="cancelSalesOrder">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择产品弹窗 -->
    <el-dialog title="选择产品" :visible.sync="selectProductDialogVisible" width="800px" append-to-body>
      <el-form :model="productQueryParams" ref="productQueryForm" size="small" :inline="true">
        <el-form-item label="产品编码" prop="productCode">
          <el-input
            v-model="productQueryParams.productCode"
            placeholder="请输入产品编码"
            clearable
            @keyup.enter.native="handleProductQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="productQueryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter.native="handleProductQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleProductQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProductQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="productLoading" :data="selectableProducts" @selection-change="handleProductSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品编码" align="center" prop="productcode" />
        <el-table-column label="产品名称" align="center" prop="productname" />
        <el-table-column label="规格" align="center" prop="specificationnumber" />
        <el-table-column label="单位" align="center" prop="unit" width="100" />
        <el-table-column label="库存数量" align="center" width="100">
          <template slot-scope="scope">
            {{ scope.row.quantity_num || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="库存状态" align="center" width="150">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.stockStatus === 'sufficient'" type="success" size="mini">
                <i class="el-icon-success"></i> 库存充足
              </el-tag>
              <el-tag v-else-if="scope.row.stockStatus === 'insufficient'" type="warning" size="mini">
                <i class="el-icon-warning"></i> 需生产
              </el-tag>
              <el-tag v-else type="danger" size="mini">
                <i class="el-icon-error"></i> 无法生产
              </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="productTotal>0"
        :total="productTotal"
        :page.sync="productQueryParams.pageNum"
        :limit.sync="productQueryParams.pageSize"
        @pagination="getProductList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
        <el-button @click="selectProductDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择客户弹窗 -->
    <el-dialog title="选择客户" :visible.sync="selectCustomerDialogVisible" width="800px" append-to-body>
      <el-form :model="customerQueryParams" ref="customerQueryForm" size="small" :inline="true">
        <el-form-item label="客户编码" prop="customerCode">
          <el-input
            v-model="customerQueryParams.customerCode"
            placeholder="请输入客户编码"
            clearable
            @keyup.enter.native="handleCustomerQuery"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="customerQueryParams.customerName"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter.native="handleCustomerQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleCustomerQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetCustomerQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="customerLoading" :data="customerList" @row-click="handleCustomerRowClick">
        <el-table-column label="客户编码" align="center" prop="customer_code" />
        <el-table-column label="客户名称" align="center" prop="customer_name" />
        <el-table-column label="联系人" align="center" prop="customer_person" />
        <el-table-column label="联系电话" align="center" prop="customer_phone" />
        <el-table-column label="地址" align="center" prop="address" show-overflow-tooltip />
      </el-table>
      
      <pagination
        v-show="customerTotal>0"
        :total="customerTotal"
        :page.sync="customerQueryParams.pageNum"
        :limit.sync="customerQueryParams.pageSize"
        @pagination="getCustomerList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listSalesOrder, getSalesOrderDetail, addSalesOrder, updateSalesOrder, getSalesOrder, delSalesOrder } from "@/api/sc/salesOrder";
import { listProduct, getProductStockStatus, checkProductCanOutbound } from "@/api/sc/product";
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers";
import { addProductionOrder } from "@/api/sc/productionOrder";
import { getDicts } from "@/api/system/dict/data";
import { getCustomerIdByName, listCustomer } from "@/api/basic/customer";

export default {
  name: "AddOrder",
  data() {
    return {
      // 防重复提交标志
      submitting: false,
      // 订单号验证状态
      orderNoValid: true,
      // 表单参数
      form: {
        orderNo: undefined,
        customerName: undefined,
        customerCode: undefined, // 客户编码
        customerId: undefined, // 客户ID
        orderSource: "1", // 默认为系统新增
        salesOrderNo: undefined,
        salesOrderId: undefined,
        deliveryDate: undefined, // 交付日期
        priority: undefined,
        remarks: undefined,
        status: "1", // 默认状态为待计划
        autoGeneratePlan: false // 自动生成生产计划标记
      },
      // 订单来源显示标签
      orderSourceLabel: '系统新增',
      // 订单来源选项
      orderSourceOptions: [],
      // 优先级选项
      priorityOptions: [],
      // 销售订单状态选项
      salesOrderStatusOptions: [],
      // 是否使用系统生产订单号
      systemOrderNo: false,
      // 是否使用系统销售订单号
      systemSalesOrderNo: false,
      // 生产订单产品列表
      productList: [],
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "生产订单号不能为空", trigger: ["blur", "change"] },
          { 
            validator: (rule, value, callback) => {
              if (this.systemOrderNo) {
                // 使用系统编号时不进行验证
                callback();
                return;
              }
              
              if (!value) {
                // 空值由必填规则处理
                callback(new Error("生产订单号不能为空"));
                return;
              }
              
              // 自定义验证逻辑
              const regex = /^SCDT\d{13}$/;
              if (!regex.test(value)) {
                callback(new Error("订单号格式错误，正确格式为SCDT+年月日(8位)+5位序号，例如SCDT2025072500011"));
              } else {
                // 验证通过
                this.orderNoValid = true;
                callback();
              }
            }, 
            trigger: ["blur", "change"]
          }
        ],
        customerName: [
          { required: true, message: "客户不能为空", trigger: ["blur", "change"] }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" }
        ]
      },
      // 销售订单弹窗
      salesOrderDialogVisible: false,
      salesOrderLoading: false,
      salesOrderList: [],
      salesOrderTotal: 0,
      selectedSalesOrder: null,
      salesOrderQueryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: '',
        customerName: ''
      },
      // 新增销售订单弹窗
      addSalesOrderDialogVisible: false,
      salesOrderForm: {
        orderCode: '',
        customerName: '',
        customerId: undefined,
        customerCode: '',
        orderDate: new Date(),
        deliveryDate: new Date(),
        status: '0',
        remark: ''
      },
      salesOrderRules: {
        orderCode: [
          { required: true, message: "销售订单号不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "订单日期不能为空", trigger: "blur" }
        ],
        deliveryDate: [
          { required: true, message: "交付日期不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "订单状态不能为空", trigger: "blur" }
        ]
      },
      // 修改销售订单弹窗
      updateSalesOrderDialogVisible: false,
      // 选择产品弹窗
      selectProductDialogVisible: false,
      productQueryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: '',
        productName: ''
      },
      productLoading: false,
      productTotal: 0,
      selectedProducts: [],
      // 销售订单产品列表
      salesOrderProducts: [],
      // 产品选择弹窗的产品列表（与生产订单产品列表分离）
      selectableProducts: [],
      // 处理表格当前行变化
      selectedSalesOrderRadio: null,
      // 选择客户弹窗
      selectCustomerDialogVisible: false,
      customerQueryParams: {
        pageNum: 1,
        pageSize: 10,
        customerCode: '',
        customerName: ''
      },
      customerLoading: false,
      customerTotal: 0,
      customerList: [],
      // 处理表格当前行变化
      selectedCustomerRadio: null,
      selectedCustomer: null
    };
  },
  created() {
    this.getDictData();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/order/add' || to.name === 'AddOrder') {
        console.log('新增订单页面路由变化，刷新数据');
        this.getDictData();
      }
    },
    systemOrderNo(val) {
      if (val) {
        this.getProductionOrderNo();
      } else {
        // 当关闭系统编号开关时，清空当前订单号
        this.form.orderNo = '';
        this.orderNoValid = true;
      }
      // 重新验证表单
      this.$nextTick(() => {
        this.validateForm('orderNo');
      });
    },
    systemSalesOrderNo(val) {
      if (val) {
        this.getSalesOrderNo();
      }
    },
    // 监听客户名称变化，获取客户ID
    'form.customerName': function(val) {
      if (val) {
        this.getCustomerIdByName(val);
      }
    }
  },
  methods: {
    // 验证生产订单号格式
    validateOrderNo() {
      if (this.systemOrderNo) {
        // 使用系统编号时不需要验证
        this.orderNoValid = true;
        return;
      }
      
      if (!this.form.orderNo) {
        // 订单号为空时不显示错误
        this.orderNoValid = true;
        return;
      }
      
      // 简化验证逻辑：检查是否以SCDT开头，后面跟13位数字
      const regex = /^SCDT\d{13}$/;
      
      // 调试日志
      console.log("验证订单号:", this.form.orderNo);
      console.log("验证结果:", regex.test(this.form.orderNo));
      
      this.orderNoValid = regex.test(this.form.orderNo);
      
      // 更新表单验证状态
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('orderNo');
        }
      });
    },
    
    // 获取字典数据
    getDictData() {
      // 获取优先级字典
      getDicts("sc_priority_type").then(response => {
        this.priorityOptions = response.data;
        console.log("优先级字典数据:", this.priorityOptions);
        if (this.priorityOptions && this.priorityOptions.length > 0) {
          // 设置默认值为普通优先级
          const defaultPriority = this.priorityOptions.find(item => item.isDefault === "Y") || this.priorityOptions.find(item => item.dictValue === "3") || this.priorityOptions[0];
          this.form.priority = defaultPriority.dictValue;
          console.log("设置默认优先级:", this.form.priority);
        } else {
          // 如果没有获取到字典数据，设置默认值
          this.form.priority = "3"; // 默认为普通优先级
          // 添加一些基本选项
          this.priorityOptions = [
            { dictLabel: "紧急", dictValue: "1" },
            { dictLabel: "高", dictValue: "2" },
            { dictLabel: "普通", dictValue: "3" },
            { dictLabel: "低", dictValue: "4" },
            { dictLabel: "计划", dictValue: "5" }
          ];
        }
      }).catch(error => {
        console.error("获取优先级字典数据失败:", error);
        // 设置默认值和基本选项
        this.form.priority = "3"; // 默认为普通优先级
        this.priorityOptions = [
          { dictLabel: "紧急", dictValue: "1" },
          { dictLabel: "高", dictValue: "2" },
          { dictLabel: "普通", dictValue: "3" },
          { dictLabel: "低", dictValue: "4" },
          { dictLabel: "计划", dictValue: "5" }
        ];
      });

      // 获取销售订单状态字典
      getDicts("sc_sales_order_status").then(response => {
        this.salesOrderStatusOptions = response.data;
      });
    },
    
    // 根据客户名称获取客户ID
    getCustomerIdByName(customerName) {
      // 避免重复请求，添加防抖处理
      if (this._customerIdByNameTimer) {
        clearTimeout(this._customerIdByNameTimer);
      }

      this._customerIdByNameTimer = setTimeout(() => {
        getCustomerIdByName(customerName)
          .then(response => {
            console.log("【客户查询】后端返回的原始响应:", JSON.stringify(response, null, 2));
            if (response.code === 200) {
              // listBasicCustomers返回的是一个列表，我们需要取第一个匹配的客户
              const customers = response.rows;
              if (customers && customers.length > 0) {
                const customer = customers[0];
                console.log("【客户查询】提取到的第一个客户对象:", JSON.stringify(customer, null, 2));
                this.form.customerId = customer.customer_id;
                this.form.customerCode = customer.customer_code;
                
                // 缓存客户信息，以便在重复提交错误时可以使用
                try {
                  sessionStorage.setItem('customerIdCache_' + customerName, JSON.stringify({
                    customer_id: customer.customer_id,
                    customer_code: customer.customer_code
                  }));
                } catch (error) {
                  console.error("缓存客户信息失败:", error);
                }
                
                console.log("已获取客户ID:", this.form.customerId);
              } else {
                console.warn("未找到客户信息:", customerName);
              }
            } else {
              console.warn("客户查询失败:", response.msg);
            }
          })
          .catch(error => {
            // 即使发生错误，也检查是否是重复提交错误，如果是，尝试从sessionStorage中获取数据
            if (error.message && error.message.includes('数据正在处理，请勿重复提交')) {
              console.warn("客户ID查询触发重复提交检查，但可能已经成功获取数据");
              // 如果已经有客户ID，保持不变
              if (this.form.customerId) {
                console.log("使用已存在的客户ID:", this.form.customerId);
              } else {
                console.warn("没有客户ID，但忽略重复提交错误继续处理");
              }
            } else {
              console.error("获取客户ID失败:", error);
            }
          });
      }, 100); // 添加100ms防抖延迟
    },
    
    // 保存按钮
    onSubmit() {
        // 如果已经在提交中，直接返回防止重复提交
        if (this.submitting) {
            console.log("请求正在处理中，请勿重复提交");
            return;
        }

        this.$refs["form"].validate(valid => {
            if (valid) {
                if (this.productList.length === 0) {
                    this.$message.warning("请添加产品信息");
                    return;
                }

                // 设置提交状态为true
                this.submitting = true;

                // 调试：打印当前form数据
                console.log("提交前的form数据:", this.form);
                console.log("销售订单ID:", this.form.salesOrderId);
                console.log("销售订单号:", this.form.salesOrderNo);
                console.log("客户名称:", this.form.customerName);
                console.log("交付日期:", this.form.deliveryDate);

                // 如果没有客户ID，但有客户名称，尝试再次获取
                if (!this.form.customerId && this.form.customerName) {
                  // 尝试再次主动获取客户ID
                  try {
                    // 先使用同步方式获取(通过本地缓存或其他方式)
                    const cachedData = sessionStorage.getItem('customerIdCache_' + this.form.customerName);
                    if (cachedData) {
                      const customer = JSON.parse(cachedData);
                      this.form.customerId = customer.customer_id;
                      this.form.customerCode = customer.customer_code;
                      console.log("从缓存恢复客户ID:", this.form.customerId);
                      this.submitOrder(); // 已获取ID，可以继续提交
                      return;
                    }
                  } catch (error) {
                    console.error("从缓存获取客户ID失败:", error);
                  }

                  // 如果没有缓存，询问用户是否继续
                  this.$confirm('未获取到客户ID，是否继续提交？', '提示', {
                    confirmButtonText: '继续提交',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    this.submitOrder();
                  }).catch(() => {
                    // 取消提交，重置提交状态
                    this.submitting = false;
                  });
                } else {
                  this.submitOrder();
                }
            }
        });
    },
    
    // 延迟函数，用于防止快速重复提交
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    
    // 提交订单
    async submitOrder() {
      // 先延迟一小段时间，避免重复提交检查
      await this.delay(100);

      // 清除之前的缓存，避免重复提交检查
      try {
        if (window.sessionStorage) {
          sessionStorage.removeItem('sessionObj');
          console.log("清除了sessionObj缓存");
        }
      } catch (error) {
        console.error("清除sessionObj失败:", error);
      }

      // 如果开启了自动编号，在提交前获取真正的编号
      if (this.systemOrderNo && this.form.orderNo) {
        try {
          const response = await getAutoNumbersConsume(1);
          if (response.code === 200) {
            this.form.orderNo = response.msg;
          }
        } catch (error) {
          this.$message.error('获取最终生产订单号失败');
          this.submitting = false;
          return;
        }
      }

      // 构建提交数据
      const submitData = {
          prodOrderCode: this.form.orderNo,
          customerName: this.form.customerName,
          customerCode: this.form.customerCode,
          customerId: this.form.customerId ? Number(this.form.customerId) : null,
          salesOrderNo: this.form.salesOrderNo,
          salesOrderId: this.form.salesOrderId ? Number(this.form.salesOrderId) : null, // 确保是数字类型
          deliveryDate: this.form.deliveryDate, // 添加交付日期
          priority: this.form.priority,
          remark: this.form.remarks,
          status: this.form.autoGeneratePlan ? "2" : "1", // 根据自动生成计划标记设置状态
          orderSource: this.form.orderSource, // 添加订单来源
          autoGeneratePlan: this.form.autoGeneratePlan, // 自动生成生产计划标记
          // 添加产品明细
          products: this.productList.map(item => ({
              productId: Number(item.productId), // 确保productId是数字类型
              productCode: item.productCode,
              productName: item.productName,
              productSfn: item.specification,
              productUnit: item.unit,
              qtyNum: Number(item.plannedQty), // 确保数量是数字类型
              deliveryDate: item.deliveryDate
          }))
      };

      console.log("=== 前端提交数据调试信息 ===");
      console.log("自动生成计划标记:", this.form.autoGeneratePlan);
      console.log("状态:", this.form.status);
      console.log("提交的数据:", submitData);
      console.log("当前form数据:", this.form);
      console.log("salesOrderId详细信息:", {
        原始值: this.form.salesOrderId,
        类型: typeof this.form.salesOrderId,
        提交值: submitData.salesOrderId,
        提交类型: typeof submitData.salesOrderId
      });
      
      // 调用API
      addProductionOrder(submitData).then(response => {
          console.log("新增响应:", response);
          this.$modal.msgSuccess("保存成功");
          this.closePage();
      }).catch(error => {
          console.error("保存失败:", error);
          
          // 处理404错误 - 临时解决方案
          if (error.response && error.response.status === 404) {
            this.$confirm('保存接口暂未实现，是否仍要关闭页面？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.closePage();
            }).catch(() => {
              // 用户取消关闭页面，重置提交状态
              this.submitting = false;
            });
          } else {
            this.$message.error("保存失败: " + (error.message || "未知错误"));
            // 重置提交状态
            this.submitting = false;
          }
      });
    },
    
    // 取消按钮
    onCancel() {
      this.closePage();
    },
    // 关闭页面
    closePage() {
      // 重置提交状态
      this.submitting = false;
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },
    // 添加产品行
    handleAddProduct() {
        this.openSelectProductDialog();
    },
    // 删除产品行
    handleDeleteProduct(index) {
        this.productList.splice(index, 1);
    },

    // --- 选择销售订单弹窗相关方法 ---
    openSalesOrderDialog() {
      this.salesOrderDialogVisible = true;
      this.getSalesOrderList();
    },
    getSalesOrderList() {
        this.salesOrderLoading = true;
        listSalesOrder(this.salesOrderQueryParams).then(response => {
          this.salesOrderList = response.rows;
          this.salesOrderTotal = response.total;
          this.salesOrderLoading = false;
        });
    },
    handleSalesOrderQuery() {
        this.salesOrderQueryParams.pageNum = 1;
        this.getSalesOrderList();
    },
    resetSalesOrderQuery() {
        this.salesOrderQueryParams.orderCode = '';
        this.salesOrderQueryParams.customerName = '';
        this.handleSalesOrderQuery();
    },
    handleSalesOrderRowSelect(row) {
        if (row) {
            this.selectedSalesOrder = row;
            this.selectedSalesOrderRadio = row.salesOrderId;
        }
    },
    confirmSelectSalesOrder() {
        if (this.selectedSalesOrder) {
            // 设置销售订单相关信息
            this.form.salesOrderNo = this.selectedSalesOrder.orderCode;
            // 确保salesOrderId是数字类型
            this.form.salesOrderId = this.selectedSalesOrder.salesOrderId ? Number(this.selectedSalesOrder.salesOrderId) : null;
            this.form.customerName = this.selectedSalesOrder.customerName;
            this.form.deliveryDate = this.selectedSalesOrder.deliveryDate;

            // 获取客户ID
            if (this.selectedSalesOrder.customerName) {
                this.getCustomerIdByName(this.selectedSalesOrder.customerName);
            }

            // 设置客户编码（如果有的话）
            if (this.selectedSalesOrder.customerCode) {
                this.form.customerCode = this.selectedSalesOrder.customerCode;
            }

            // 选择销售订单后清空之前的产品列表
            this.productList = [];
            this.$nextTick(() => {
                // 获取销售订单明细
                this.loadSalesOrderDetail(this.selectedSalesOrder.salesOrderId);
            });

            console.log("选择销售订单后的form数据:", this.form);
            console.log("salesOrderId类型:", typeof this.form.salesOrderId, "值:", this.form.salesOrderId);
            this.$message.success("已选择销售订单：" + this.selectedSalesOrder.orderCode);
        }
        this.salesOrderDialogVisible = false;
    },
    handleSalesOrderDoubleClick(row) {
      this.form.salesOrderNo = row.orderCode;
      this.form.customerName = row.customerName;

      // 清空产品列表
      this.productList = [];
      
      // 获取销售订单ID，兼容不同字段名称
      const salesOrderId = row.salesOrderId;
      this.form.salesOrderId = salesOrderId;
      
      // 获取客户ID
      if (row.customerName) {
        this.getCustomerIdByName(row.customerName);
      }
      
      // 调试输出行数据
      console.log("选中的销售订单行数据:", row);
      console.log("销售订单ID:", salesOrderId);
      
      if (salesOrderId) {
        this.$nextTick(() => {
          // 加载销售订单明细
          this.loadSalesOrderDetail(salesOrderId);
        });
        
        this.$message.success("已选择销售订单：" + row.orderCode);
      } else {
        this.$message.error("获取销售订单ID失败，无法加载明细信息");
        console.error("销售订单行数据缺少ID字段:", row);
      }
      
      this.salesOrderDialogVisible = false;
    },
    handleAddSalesOrder() {
        this.addSalesOrderDialogVisible = true;
    },
    handleUpdateSalesOrder() {
        if (!this.selectedSalesOrder) {
            this.$message.warning("请选择一个销售订单进行修改");
            return;
        }
        this.updateSalesOrderDialogVisible = true;
        this.salesOrderProducts = []; // 清空产品列表
        
        // 获取销售订单ID，兼容不同字段名称
        const salesOrderId = this.selectedSalesOrder.salesOrderId;
        
        console.log("修改销售订单数据:", this.selectedSalesOrder);
        console.log("销售订单ID:", salesOrderId);
        
        if (!salesOrderId) {
            this.$message.error("获取销售订单ID失败");
            return;
        }
        
        // 使用getSalesOrder API获取完整的销售订单数据
        getSalesOrder(salesOrderId).then(response => {
            if (response.data) {
                this.salesOrderForm = response.data;
                
                // 获取销售订单明细
                getSalesOrderDetail(salesOrderId).then(detailRes => {
                    if (detailRes.rows && detailRes.rows.length > 0) {
                        // 将销售订单明细转换为产品列表
                        const productIds = detailRes.rows.map(item => item.productId);
                        
                        // 获取产品库存状态
                        getProductStockStatus(productIds).then(stockRes => {
                            const stockData = stockRes.data || [];
                            
                            // 构建产品列表
                            this.salesOrderProducts = detailRes.rows.map(detail => {
                                const stockInfo = stockData.find(item => item.productId === detail.productId) || {};
                                return {
                                    detailId: detail.id, // 明细ID
                                    id: detail.productId,
                                    productCode: detail.productCode,
                                    productName: detail.productName,
                                    specification: detail.specification || '',
                                    unit: detail.unit || '件',
                                    price: detail.price || 0,
                                    qty: detail.qty || 0,
                                    maxQty: stockInfo.quantity_num || 999,
                                    stockQty: stockInfo.quantity_num || 0,
                                    stockStatus: stockInfo.status || 'insufficient'
                                };
                            });
                        });
                    }
                });
            } else {
                this.salesOrderForm = {
                    id: salesOrderId,
                    orderCode: this.selectedSalesOrder.orderCode,
                    customerName: this.selectedSalesOrder.customerName,
                    orderDate: this.selectedSalesOrder.orderDate,
                    deliveryDate: this.selectedSalesOrder.deliveryDate,
                    status: this.selectedSalesOrder.status || "0",
                    remark: this.selectedSalesOrder.remark || ""
                };
            }
        }).catch((error) => {
            console.error("获取销售订单详情失败:", error);
            // 如果API调用失败，仍使用列表中的数据
            this.salesOrderForm = {
                id: salesOrderId,
                orderCode: this.selectedSalesOrder.orderCode,
                customerName: this.selectedSalesOrder.customerName,
                orderDate: this.selectedSalesOrder.orderDate,
                deliveryDate: this.selectedSalesOrder.deliveryDate,
                status: this.selectedSalesOrder.status || "0",
                remark: this.selectedSalesOrder.remark || ""
            };
        });
    },
    handleDeleteSalesOrder() {
        if (!this.selectedSalesOrder) {
            this.$message.warning("请选择一个销售订单进行删除");
            return;
        }
        const salesOrderId = this.selectedSalesOrder.salesOrderId;
        const orderCode = this.selectedSalesOrder.orderCode;
        this.$modal.confirm('是否确认删除销售订单编号为"' + orderCode + '"的数据项?').then(() => {
            return delSalesOrder(salesOrderId);
        }).then(() => {
            this.getSalesOrderList();
            this.$modal.msgSuccess("删除成功");
            this.selectedSalesOrder = null; // 清空选中
            this.selectedSalesOrderRadio = null;
        }).catch(() => {});
    },
    // 加载销售订单明细
    loadSalesOrderDetail(salesOrderId) {
        if (!salesOrderId) {
            this.$message.error("销售订单ID不能为空");
            return;
        }
        console.log("正在加载销售订单明细, ID:", salesOrderId);
        getSalesOrderDetail(salesOrderId).then(response => {
            console.log("销售订单明细响应数据：", response);
            if (response.rows && response.rows.length > 0) {
                // 清空之前的产品列表
                this.productList = [];
                
                // 获取所有产品ID
                const productIds = response.rows.map(detail => detail.productId);
                
                // 获取默认交付日期
                const defaultDeliveryDate = this.selectedSalesOrder ? this.selectedSalesOrder.deliveryDate : new Date();
                
                // 获取产品库存状态
                getProductStockStatus(productIds).then(stockRes => {
                    const stockData = stockRes.data || [];
                    console.log("产品库存状态数据：", stockData);
                    
                    // 详细记录每条明细数据
                    response.rows.forEach((detail, index) => {
                        console.log(`明细 ${index + 1}:`, detail);
                        
                        // 查找对应的库存状态
                        const stockInfo = stockData.find(item => Number(item.productId) === Number(detail.productId)) || {};
                        console.log(`产品 ${detail.productName} 的库存信息:`, stockInfo);
                        
                        // 将销售订单明细转换为产品列表
                        this.productList.push({
                            productId: detail.productId,
                            productCode: detail.productCode || String(detail.productId),
                            productName: detail.productName || detail.remark || '未知产品',
                            specification: detail.specification || '',
                            unit: detail.unit || '件',
                            plannedQty: detail.qty || 0,
                            price: detail.price || 0,
                            remark: detail.remark || '',
                            deliveryDate: defaultDeliveryDate,
                            quantity_num: detail.quantity_num || stockInfo.quantity_num || 0,
                            stockStatus: stockInfo.status || (detail.quantity_num > 0 ? 'sufficient' : 'insufficient')
                        });
                    });
                    console.log("产品列表数据：", this.productList);
                }).catch(error => {
                    console.error("获取产品库存状态失败：", error);
                    
                    // 获取默认交付日期
                    const defaultDeliveryDate = this.selectedSalesOrder ? this.selectedSalesOrder.deliveryDate : new Date();
                    
                    // 即使获取库存状态失败，仍然加载产品列表
                    response.rows.forEach((detail, index) => {
                        this.productList.push({
                            productId: detail.productId,
                            productCode: detail.productCode || String(detail.productId),
                            productName: detail.productName || detail.remark || '未知产品',
                            specification: detail.specification || '',
                            unit: detail.unit || '件',
                            plannedQty: detail.qty || 0,
                            price: detail.price || 0,
                            remark: detail.remark || '',
                            deliveryDate: defaultDeliveryDate,
                            quantity_num: detail.quantity_num || 0,
                            stockStatus: detail.quantity_num > 0 ? 'sufficient' : 'insufficient'
                        });
                    });
                    this.$message.success(`成功加载 ${response.rows.length} 条产品信息，但库存状态获取失败`);
                });
            } else {
                this.$message.warning("该销售订单没有明细信息");
            }
        }).catch(error => {
            console.error("加载销售订单明细失败：", error);
            this.$message.error("加载销售订单明细失败");
        });
    },
    // 新增销售订单表单提交
    async submitSalesOrderForm() {
      this.$refs["addSalesOrderForm"].validate(async valid => {
        if (valid) {
          // 检查是否添加了产品
          if (this.salesOrderProducts.length === 0) {
            this.$message.warning("请至少添加一个产品");
            return;
          }

          // 如果开启了自动编号，在提交前获取真正的编号
          if (this.systemSalesOrderNo && this.salesOrderForm.orderCode) {
            try {
              const response = await getAutoNumbersConsume(2);
              if (response.code === 200) {
                this.salesOrderForm.orderCode = response.msg;
              }
            } catch (error) {
              this.$message.error('获取最终销售订单号失败');
              return;
            }
          }

          // 构建提交数据
          const submitData = {
            ...this.salesOrderForm,
            details: this.salesOrderProducts.map(item => ({
              id: item.detailId, // 如果是已有明细，保留ID
              productId: item.id,
              productCode: item.productCode,
              productName: item.productName,
              specification: item.specification,
              unit: item.unit,
              price: item.price,
              qty: item.qty
            }))
          };
          
          // 提交新增销售订单
          addSalesOrder(submitData).then(response => {
            this.$modal.msgSuccess("新增销售订单成功");
            
            // 检查是否有可以直接出库的产品
            const productIds = this.salesOrderProducts.map(item => item.id);
            checkProductCanOutbound(productIds).then(res => {
              if (res.data && res.data.canOutbound) {
                // 提示用户可以直接出库
                this.$confirm('该销售订单中的产品库存充足，是否直接进行销售出库操作？', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'success'
                }).then(() => {
                  // 跳转到仓库销售出库页面
                  this.addSalesOrderDialogVisible = false;
                  this.salesOrderDialogVisible = false;
                  this.$nextTick(() => {
                    this.$router.push('/ck/SalesOutbound');
                  });
                }).catch(() => {
                  // 用户选择不直接出库，关闭弹窗
                  this.addSalesOrderDialogVisible = false;
                  this.getSalesOrderList();
                });
              } else {
                // 不能直接出库，关闭弹窗
                this.addSalesOrderDialogVisible = false;
                this.getSalesOrderList();
                
                // 检查是否需要生产
                const insufficientProducts = this.salesOrderProducts.filter(item => item.stockStatus === 'insufficient');
                if (insufficientProducts.length > 0) {
                  this.$confirm('该销售订单中的部分产品需要生产，是否创建生产订单？', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                  }).then(() => {
                    // 自动填充生产订单信息
                    this.form.salesOrderNo = response.data.orderCode;
                    this.form.customerName = response.data.customerName;
                    
                    // 将需要生产的产品添加到生产订单产品列表
                    this.productList = insufficientProducts.map(item => ({
                      productCode: item.productCode,
                      productName: item.productName,
                      specification: item.specification,
                      unit: item.unit,
                      plannedQty: item.qty,
                      deliveryDate: this.salesOrderForm.deliveryDate
                    }));
                    
                    this.$message.info("请完善生产订单信息后保存");
                  }).catch(() => {
                    // 用户选择不创建生产订单
                  });
                }
              }
            });
          }).catch(() => {});
        }
      });
    },
    cancelSalesOrder() {
      if (this.addSalesOrderDialogVisible) {
        this.addSalesOrderDialogVisible = false;
      }
      if (this.updateSalesOrderDialogVisible) {
        this.updateSalesOrderDialogVisible = false;
      }
    },
    // 关闭所有弹窗
    closeAllDialogs() {
      this.salesOrderDialogVisible = false;
      this.addSalesOrderDialogVisible = false;
      this.updateSalesOrderDialogVisible = false;
      this.selectProductDialogVisible = false;
      this.selectCustomerDialogVisible = false;
    },
    // 重置销售订单表单
    resetSalesOrderForm() {
      this.salesOrderForm = {
        orderCode: '',
        customerName: '',
        customerId: undefined,
        customerCode: '',
        orderDate: new Date(),
        deliveryDate: new Date(),
        status: '0',
        remark: ''
      };
      this.salesOrderProducts = [];
      this.systemSalesOrderNo = false;
      if (this.$refs["addSalesOrderForm"]) {
        this.$refs["addSalesOrderForm"].resetFields();
      }
    },
    // 修改销售订单表单提交
    updateSalesOrderForm() {
      this.$refs["updateSalesOrderForm"].validate(valid => {
        if (valid) {
          // 检查是否添加了产品
          if (this.salesOrderProducts.length === 0) {
            this.$message.warning("请至少添加一个产品");
            return;
          }
          
          // 构建提交数据
          const submitData = {
            ...this.salesOrderForm,
            details: this.salesOrderProducts.map(item => ({
              id: item.detailId, // 如果是已有明细，保留ID
              productId: item.id,
              productCode: item.productCode,
              productName: item.productName,
              specification: item.specification,
              unit: item.unit,
              price: item.price,
              qty: item.qty
            }))
          };
          
          // 提交修改销售订单
          updateSalesOrder(submitData).then(response => {
            this.$modal.msgSuccess("修改销售订单成功");
            this.updateSalesOrderDialogVisible = false;
            // 刷新销售订单列表
            this.getSalesOrderList();
            
            // 检查是否有可以直接出库的产品
            const productIds = this.salesOrderProducts.map(item => item.id);
            checkProductCanOutbound(productIds).then(res => {
              if (res.data && res.data.canOutbound) {
                // 提示用户可以直接出库
                this.$confirm('该销售订单中的产品库存充足，是否直接进行销售出库操作？', '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'success'
                }).then(() => {
                  // 跳转到仓库销售出库页面
                  this.updateSalesOrderDialogVisible = false;
                  this.salesOrderDialogVisible = false;
                  this.$nextTick(() => {
                    this.$router.push('/ck/SalesOutbound');
                  });
                }).catch(() => {
                  // 用户选择不直接出库
                  this.updateSalesOrderDialogVisible = false;
                  this.getSalesOrderList();
                });
              } else {
                // 检查是否需要生产
                const insufficientProducts = this.salesOrderProducts.filter(item => item.stockStatus === 'insufficient');
                if (insufficientProducts.length > 0) {
                  this.$confirm('该销售订单中的部分产品需要生产，是否创建生产订单？', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                  }).then(() => {
                    // 自动填充生产订单信息
                    this.form.salesOrderNo = this.salesOrderForm.orderCode;
                    this.form.customerName = this.salesOrderForm.customerName;
                    
                    // 将需要生产的产品添加到生产订单产品列表
                    this.productList = insufficientProducts.map(item => ({
                      productCode: item.productCode,
                      productName: item.productName,
                      specification: item.specification,
                      unit: item.unit,
                      plannedQty: item.qty,
                      deliveryDate: this.salesOrderForm.deliveryDate
                    }));
                    
                    this.$message.info("请完善生产订单信息后保存");
                  }).catch(() => {
                    // 用户选择不创建生产订单
                  });
                }
              }
            });
          }).catch(() => {});
        }
      });
    },
    // 打开选择产品弹窗
    openSelectProductDialog() {
      this.selectProductDialogVisible = true;
      this.selectedProducts = [];
      this.getProductList();
    },
    // 处理产品选择
    handleProductSelectionChange(selection) {
      console.log("选中的产品:", selection);
      this.selectedProducts = selection;
    },
    // 处理产品删除
    handleDeleteOrderProduct(index) {
      this.salesOrderProducts.splice(index, 1);
    },
    // 处理产品查询
    handleProductQuery() {
      this.productQueryParams.pageNum = 1;
      this.getProductList();
    },
    // 重置产品查询
    resetProductQuery() {
      this.resetForm("productQueryForm");
      this.handleProductQuery();
    },
    // 获取产品列表
    getProductList() {
      this.productLoading = true;
      
      console.log("获取产品列表，参数:", this.productQueryParams);
      
      listProduct(this.productQueryParams).then(response => {
        // 清空现有数据
        this.selectableProducts = [];
        
        // 调试输出原始响应数据
        console.log("产品API原始响应:", JSON.stringify(response));
        
        if (!response.rows || response.rows.length === 0) {
          console.warn("API返回的产品列表为空");
          this.productTotal = 0;
          this.productLoading = false;
          return;
        }
        
        // 处理返回的数据
        this.selectableProducts = response.rows.map((product, index) => ({
          ...product,
          productid: product.product_id || product.productId || product.productid || index + 1, 
          productcode: product.product_code || product.productCode || product.productcode || `TEMP-${index + 1}`,
          productname: product.product_name || product.productName || product.productname || `未命名产品-${index + 1}`,
          specificationnumber: product.product_sfn || product.specification || product.specificationnumber || '',
          unit: product.product_unit || product.unit || '件',
          quantity_num: product.quantity_num || 0,  // 直接使用后端返回的库存数量
          stockStatus: product.quantity_num > 0 ? 'sufficient' : 'insufficient'  // 根据库存数量设置状态
        }));
        
        // 更新总数
        this.productTotal = response.total;
        
        // 如果有产品，获取库存状态
        if (this.selectableProducts.length > 0) {
          // 获取产品ID列表
          const productIds = this.selectableProducts
            .map(item => item.productid)
            .filter(id => id != null);
          
          // 获取库存状态
          if (productIds.length > 0) {
            getProductStockStatus(productIds).then(res => {
              // 处理库存状态
              if (res.code === 200 && res.data && res.data.length > 0) {
                // 更新产品库存信息
                this.selectableProducts.forEach((product, index) => {
                  const productId = product.productid;
                  const stockInfo = res.data.find(item => Number(item.productId) === Number(productId));
                  
                  if (stockInfo) {
                    this.$set(this.selectableProducts[index], 'quantity_num', stockInfo.quantity_num || 0);
                    this.$set(this.selectableProducts[index], 'stockStatus', stockInfo.status || 'insufficient');
                    this.$set(this.selectableProducts[index], 'maxQty', stockInfo.quantity_num || 999);
                  }
                });
              }
              console.log("更新库存后的产品列表:", this.selectableProducts);
            }).catch(error => {
              console.error("获取库存状态失败:", error);
            }).finally(() => {
              this.productLoading = false;
            });
          } else {
            this.productLoading = false;
          }
        } else {
          this.productLoading = false;
        }
      }).catch(error => {
        console.error("获取产品列表失败:", error);
        this.productLoading = false;
      });
    },
    // 确认选择产品
    confirmSelectProduct() {
      if (this.selectedProducts.length === 0) {
        this.$message.warning("请至少选择一个产品");
        return;
      }
      
      console.log("选中的产品:", this.selectedProducts);
      
      // 判断当前是在销售订单弹窗还是生产订单中选择产品
      if (this.addSalesOrderDialogVisible || this.updateSalesOrderDialogVisible) {
        // 将选中的产品添加到销售订单产品列表
        this.selectedProducts.forEach(product => {
          // 获取产品ID，优先使用productid字段
          const productId = Number(product.productid);
          console.log(`添加产品到销售订单: ${product.productname}, ID: ${productId}, 库存: ${product.quantity_num}`);
          
          if (!productId) {
            console.error("产品ID无效:", product);
            this.$message.warning(`产品 ${product.productname || '未知产品'} 的ID无效，无法添加`);
            return;
          }
          
          // 检查是否已经添加过该产品
          const existIndex = this.salesOrderProducts.findIndex(item => Number(item.id) === productId);
          if (existIndex !== -1) {
            this.$message.warning(`产品 ${product.productname} 已添加，请勿重复添加`);
            return;
          }
          
          // 添加产品到销售订单产品列表
          this.salesOrderProducts.push({
            id: productId,
            productCode: product.productcode || '',
            productName: product.productname || '',
            specification: product.specificationnumber || '',
            unit: product.unit || '',
            price: product.saleprice || 0,
            qty: 1,
            maxQty: product.quantity_num || 999,
            stockQty: product.quantity_num || 0,
            stockStatus: product.stockStatus || 'insufficient'
          });
        });
        
        console.log("更新后的销售订单产品列表:", this.salesOrderProducts);
      } else {
        // 将选中的产品添加到生产订单产品列表
        this.selectedProducts.forEach(product => {
          // 获取产品ID，优先使用productid字段
          const productId = Number(product.productid);
          console.log(`添加产品到生产订单: ${product.productname}, ID: ${productId}, 库存: ${product.quantity_num}, 状态: ${product.stockStatus}`);
          
          if (!productId) {
            console.error("产品ID无效:", product);
            this.$message.warning(`产品 ${product.productname || '未知产品'} 的ID无效，无法添加`);
            return;
          }
          
          // 检查是否已经添加过该产品
          const existIndex = this.productList.findIndex(item => Number(item.productId) === productId);
          if (existIndex !== -1) {
            this.$message.warning(`产品 ${product.productname} 已添加，请勿重复添加`);
            return;
          }
          
          // 添加产品到生产订单产品列表
          this.productList.push({
            productId: productId,
            productCode: product.productcode || '',
            productName: product.productname || '',
            specification: product.specificationnumber || '',
            unit: product.unit || '',
            plannedQty: 10,
            deliveryDate: new Date(),
            quantity_num: product.quantity_num || 0,
            stockStatus: product.stockStatus || 'insufficient'
          });
        });
        
        console.log("更新后的生产订单产品列表:", this.productList);
      }
      
      this.selectProductDialogVisible = false;
    },
    // 处理表格当前行变化
    handleCurrentRowChange(currentRow) {
      if (currentRow) {
        // 获取销售订单ID，兼容不同字段名称
        const salesOrderId = currentRow.id || currentRow.orderid || currentRow.salesOrderId;
        this.selectedSalesOrderRadio = salesOrderId;
        this.selectedSalesOrder = currentRow;
        this.form.salesOrderId = salesOrderId;
      } else {
        this.selectedSalesOrderRadio = null;
        this.selectedSalesOrder = null;
        this.form.salesOrderId = null;
      }
    },

    handleRowClick(row) {
      // 获取销售订单ID，兼容不同字段名称
      const salesOrderId = row.id || row.orderid || row.salesOrderId;
      this.selectedSalesOrderRadio = salesOrderId;
      this.selectedSalesOrder = row;
      this.form.salesOrderId = salesOrderId;
      this.$refs.salesOrderTable.setCurrentRow(row);
    },

    // 获取自动生成的生产订单号
    getProductionOrderNo() {
      console.log("开始获取生产订单号...");
      getAutoNumbers(1).then(response => {
        console.log("生产订单号API响应:", response);
        if (response.code === 200) {
          this.form.orderNo = response.msg;
        } else {
          this.$message.error("获取生产订单号失败：" + response.msg);
        }
      }).catch(error => {
        console.error("获取生产订单号异常：", error);
        this.$message.error("获取生产订单号异常，请稍后重试");
      });
    },
    
    // 获取自动生成的销售订单号
    getSalesOrderNo() {
      console.log("开始获取销售订单号...");
      getAutoNumbers(2).then(response => {
        console.log("销售订单号API响应:", response);
        if (response.code === 200) {
          this.salesOrderForm.orderCode = response.msg;
        } else {
          this.$message.error("获取销售订单号失败：" + response.msg);
        }
      }).catch(error => {
        console.error("获取销售订单号异常：", error);
        this.$message.error("获取销售订单号异常，请稍后重试");
      });
    },
    // 打开选择客户弹窗
    openSelectCustomerDialog() {
      this.selectCustomerDialogVisible = true;
      this.getCustomerList();
    },

    // 处理客户选择
    handleCustomerRowClick(row) {
      this.logObject("选中的客户", row);
      
      // 设置客户信息，适配后端返回的字段名
      if (row) {
        // 判断当前是在销售订单表单中还是主表单中
        if (this.addSalesOrderDialogVisible || this.updateSalesOrderDialogVisible) {
          // 销售订单表单
          this.salesOrderForm.customerName = row.customer_name || '';
          this.salesOrderForm.customerId = row.customer_id;
          this.salesOrderForm.customerCode = row.customer_code || '';
        } else {
          // 主表单
          this.form.customerName = row.customer_name || '';
          this.form.customerId = row.customer_id;
          this.form.customerCode = row.customer_code || '';
          console.log("已更新主表单客户信息:", this.form.customerName, this.form.customerId);
        }
      }
      
      this.selectCustomerDialogVisible = false;
    },

    // 获取客户列表
    getCustomerList() {
      this.customerLoading = true;
      
      // 构建查询参数，适配后端接口需要的参数名称
      const queryParams = {
        pageNum: this.customerQueryParams.pageNum,
        pageSize: this.customerQueryParams.pageSize
      };
      
      // 只有当有值时才添加查询条件
      if (this.customerQueryParams.customerCode) {
        queryParams.customer_code = this.customerQueryParams.customerCode;
      }
      
      if (this.customerQueryParams.customerName) {
        queryParams.customer_name = this.customerQueryParams.customerName;
      }
      
      this.logObject("客户查询参数", queryParams);
      
      listCustomer(queryParams).then(response => {
        this.logObject("客户列表原始数据", response);
        this.customerList = response.rows || [];
        this.customerTotal = response.total || 0;
        this.customerLoading = false;
      }).catch(error => {
        console.error("获取客户列表失败:", error);
        this.customerLoading = false;
      });
    },

    // 重置客户查询
    resetCustomerQuery() {
      this.customerQueryParams.customerCode = '';
      this.customerQueryParams.customerName = '';
      this.handleCustomerQuery();
    },

    // 处理客户查询
    handleCustomerQuery() {
      this.customerQueryParams.pageNum = 1;
      this.getCustomerList();
    },
    
    // 调试打印对象
    logObject(title, obj) {
      console.log(title + ":", JSON.stringify(obj, null, 2));
    },
    // 销售订单状态字典翻译
    salesOrderStatusFormat(row) {
      const status = row.status;
      const dict = this.salesOrderStatusOptions.find(item => item.dictValue === status);
      return dict ? dict.dictLabel : status;
    },

    // 计算实际生产数量
    getActualProductionQty(row) {
      const demandQty = row.plannedQty || 0;
      const stockQty = row.quantity_num || 0;
      const actualQty = demandQty - stockQty;
      return actualQty > 0 ? actualQty : 0;
    },

    // 更新实际生产数量（当需求数量变化时）
    updateActualProduction(row) {
      // 这个方法主要用于触发界面更新，实际计算在getActualProductionQty中
      this.$forceUpdate();
    },

    // 在methods中添加新方法
    validateForm(field) {
      // 检查表单是否已创建
      if (this.$refs.form) {
        // 如果提供了特定字段，只验证该字段
        if (field) {
          this.$refs.form.validateField(field);
        } else {
          // 否则验证整个表单
          this.$refs.form.validate();
        }
      }
    }
  }
};
</script>

<style scoped>
.box-card {
  width: 100%;
}
.input-with-switch {
  display: flex;
  align-items: center;
  width: 100%;
}
.switch-right {
  margin-left: 20px;
  min-width: 120px;
}

/* 销售订单选择弹窗样式 */
.sales-order-dialog {
  margin: -20px -20px;
  padding: 0 20px;
  box-sizing: border-box;
}
.sales-order-dialog .el-table {
  width: 100% !important;
  margin-bottom: 10px;
}
.sales-order-dialog .el-table ::v-deep .current-row {
  background-color: #f5f7fa;
}
</style> 